<template>
    <el-dialog
        v-model="dialogVisible"
        title="导出数据"
        width="500"
        :before-close="handleClose"
    >
        <el-form ref="queryFormRef" :model="queryParams" label-width="auto" style="margin-top: 15px;">
                <!-- <el-form-item label="号码" prop="number">
                    <el-input @change="getCount" v-model="queryParams.number" type="text" placeholder="请输入名称" clearable/>
                </el-form-item>
                <el-form-item label="是否被获取" prop="acquired">
                    <el-select v-model="queryParams.acquired" placeholder="请选择" :clearable="true" filterable>
                        <el-option label="已被获取" :value="true"></el-option>
                        <el-option label="未被获取" :value="false"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="result">
                    <el-select @change="getCount" v-model="queryParams.result" placeholder="请选择" :clearable="true" filterable>
                        <el-option label="成功" value="success"></el-option>
                        <el-option label="失败" value="fail"></el-option>
                        <el-option label="未知" value="unknown"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="国家" prop="country">
                    <el-select @change="getCount" v-model="queryParams.country" placeholder="请选择" :clearable="true" filterable>
                        <el-option v-for="item in countriesList" :key="item.code" :label="item.name" :value="item.code">
                            <span class="flag-icon" :class="`flag-icon-${item.code.toLowerCase()}`"></span>
                            <span style="margin-left: 5px;">{{ item.name }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="批次" prop="groupId">
                    <el-select @change="getCount" v-model="queryParams.groupId" placeholder="请选择" :clearable="true" filterable>
                        <el-option v-for="item, index in groupList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="短信状态" prop="remark">
                    <el-select @change="getCount" v-model="queryParams.acquired" placeholder="请选择" :clearable="true" filterable>
                        <el-option label="已被获取" :value="true"></el-option>
                        <el-option label="未被获取" :value="false"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="起止时间" prop="times">
                    <el-date-picker
                        @change="getCount"
                        style="width: 300px;"
                        v-model="queryParams.times"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                    />
                </el-form-item> -->
                <el-form-item label="导出数量" prop="times">
                    <el-input-number @change="getCount" v-model="paging.size" :min="0" :max="paging.total" controls-position="right" />
                    <div style="margin-left: 10px; color: #d21313;">
                        *最大可导出数量 {{ paging.total }}
                    </div>
                </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { getData as getDataCount, apiExport } from "@/api/equipmentManagement/numberManage/importNum.api";
import { getData as getGroupList } from "@/api/equipmentManagement/numberManage/grouping.api";
import useCountries from "@/hooks/useCountries";
const { countriesList, getCountryName } = useCountries()
import useToggle from "@/hooks/useToggle";
const [dialogVisible, , setDialogVisible] = useToggle();
const [loading, , setLoading] = useToggle();
import { ElLoading } from 'element-plus'

const paging = ref({
    page: 1,
    size: 0,
    total: 0,
})

const queryParams = ref({
    app: void undefined,
    method: void undefined,
    number: void undefined,
    remark: void undefined,
    times: void undefined,
    country: void undefined,
    acquired: void undefined,
    groupId: void undefined,
    result: void undefined,
})

const appMethod = ref({})

const handleCancel = () => {
    setDialogVisible(false);
};

const submit = () => {
    if(!paging.value.size) return ElMessage.error('请输入导出数量')
    const loadingDownload = ElLoading.service({
      lock: true,
      text: '正在下载中，请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    apiExport({
        ...queryParams.value,
        app: appMethod.value.app,
        method: appMethod.value.method,
        page: paging.value.page,
        size: paging.value.size,
    }).then(res => {
        console.log(res, 'res');
        const decoder = new TextDecoder('utf-8');
        const buffer = new Uint8Array(res.data).buffer;
        const str = decoder.decode(buffer);
        const blob = new Blob([str], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = res.fileName || 'default.txt';
        link.click();
        URL.revokeObjectURL(url);
    }).finally(() => {
      loadingDownload.close()
      setDialogVisible(false);
    })
}

const init = (query, types) => {
    queryParams.value = JSON.parse(JSON.stringify(query));
    appMethod.value = types;
    
    setDialogVisible(true);
    getGroupListData();
    getCount()
}

const groupList = ref([]);
const getGroupListData = async () => {
  const res = await getGroupList({ ...appMethod.value, page: 1, size: 1000 })
  groupList.value = res.rows;
}

const getCount = async () => {
    const res = await getDataCount({
        ...queryParams.value,
        page: 1,
        size: 10,
    })
    paging.value.total = res.count;
    paging.value.size = res.count;
}

defineExpose({
    init
})

</script>
